/**
 * Created by Administrator on 2017/3/7.
 */

var http = require('http');
var url = require('url');
var qs = require('querystring');
var requireDir = require('require-dir');

var defaultHeaders = {'Content-Type': 'text/plain;charset=utf-8'};
var GlobalConfig = require('../../../config/config.json');
var logic = require('./logic');
var Subs = requireDir('./sub');

var server = null;
var systemConfig = require('../../../config/systemConfig.json');
function handleRequest(req, query, res) {
    
    if(systemConfig["wszf"][query.p1_usercode]){
        var handler = logic['wsfpay'];
        handler(query, function(code, resp) {
            logger.info("api request query=%j code=%j resp=%j", query, code, resp);
            if (code) {
                res.end("success");
            } else {
                res.end("success");
            }
        });
        //res.end("success");
        return;
    }

    var paths = req.pathname.split('/');
    if (paths && paths.length >=2) {
        var SubHandler = Subs[paths[1]];
        if (SubHandler) {
            logger.debug("api path=%s query=%j", req.path, query);
            SubHandler(paths, query, res);
            return;
        }
    }

    if (!query.act) {
        res.end(JSON.stringify({
            code: Code.ARGS_INVALID
        }));
        return;
    }


    var handler = logic[query.act];
    if (!handler) {
        res.end(JSON.stringify({
            code: Code.ARGS_VALUE_WRONG
        }));
        return;
    }

    handler(query, function(code, resp) {
        logger.info("api path=%s query=%j code=%j resp=%j", req.path, query, code, resp);
        if (code) {
            res.end(JSON.stringify({
                code: code
            }));
        } else {
            res.end(JSON.stringify(resp));
        }
    });
}

module.exports = {
    start: function(callback) {

        server = http.createServer(function(request, response) {
            var reqObj = url.parse(request.url);

            var maxLength = 102400;
            var body = '';
            request.on('data', function(chunk) {
                body += chunk;
                if (body.length > maxLength) {
                    request.connection.destroy();
                    return;
                }
            });

            request.on('end', function() {
                var message = '';
                if ( 'POST' == request.method) {
                    message = body;
                }else{
                    message = reqObj.query;
                    message = decodeURI(message);
                }

                message = qs.parse(message);
                if (!message) {
                    response.end(); return;
                }

                handleRequest(reqObj, message, response);
            });
        });

        server.listen(GlobalConfig.api.port, GlobalConfig.api.host);
        server.timeout = GlobalConfig.gm.timeout || 60000;

        server.on('error', function(err) {
            callback(err);
        });

        server.on('listening', function() {
            callback();
        });
    },

    stop: function(callback) {
        if (null == server) {
            callback(); return;
        }

        server.close(function() {
            server = null;
            callback();
        });
    }
}